import {Component} from "@angular/core";
import {AlertController, IonicPage, NavController, NavParams} from "ionic-angular";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {UserService} from "../../services/user.service";

@IonicPage()
@Component({
  selector: 'page-bind-sub-account',
  templateUrl: 'bind-sub-account.html',
})
export class BindSubAccountPage {
  public validateForm: FormGroup = this.fb.group({
    account: [null, [Validators.required]],
  });//表单
  public realName: string;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              private fb: FormBuilder, private userService: UserService,
              private alertCtrl: AlertController) {
  }

  ionViewDidLoad() {

  }

  getUser() {
    if (!this.validateForm.value.account || this.validateForm.value.account == '') {
      this.realName = undefined;
      return;
    }
    this.userService.getUser(this.validateForm.value.account).then((data: any) => {
      if (data) this.realName = data.realName;
      else this.realName = '?';
    })
  }

  beforeBindAccount($event) {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    this.passwordPrompt();
  }

  passwordPrompt() {
    let alert = this.alertCtrl.create({
      title: '被关联账户密码',
      inputs: [
        {
          name: 'password',
          type: 'password',
          placeholder: '请输入被关联账户密码'
        }
      ],
      buttons: [
        {
          text: '确认',
          handler: data => {
            if (!data.password || data.password === '') return false;
            else {
              let formData = Object.assign(this.validateForm.value);
              formData.password = data.password;
              this.bindAccount(formData);
            }
          }
        }
      ]
    });
    alert.present();
  }

  bindAccount(formData){
    this.userService.bindAccount(formData).then(res => {
      this.navCtrl.pop()
    })
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}

